package RegexBubble;

import java.io.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexpClass {
	public static void sortFile(String filepath) {
		try {
			// Open the file that is the first
			// command line parameter
			FileInputStream fstream = new FileInputStream(filepath);
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			
			ArrayList<String> array = new ArrayList<String>();
			// Read File Line By Line
			String strLine;
			while ((strLine = br.readLine()) != null) {
				// Print the content on the console
			
				array= findDecimals(strLine,array);
			}
			// Close the input stream
			in.close();
			double[] doubarr = new double[array.size()];
			for(int i=0;i<doubarr.length;i++)
				doubarr[i]=new Double(array.get(i));
			BubbleSortClass.bubblesort(doubarr);
			writeToFile(doubarr);
			
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}
	private static ArrayList<String> findDecimals(String str, ArrayList<String> array){
		Pattern pattern = Pattern.compile("-?\\d+([\\.\\,]\\d+)?");
		Matcher matcher= pattern.matcher(str);
		while(matcher.find()){
			array.add(matcher.group().replace(',', '.'));
		}
		return array;
	}

	private static void writeToFile(double[] doubarr) {
		try {
			// Create file
			FileWriter fstream = new FileWriter("after.txt");
			BufferedWriter out = new BufferedWriter(fstream);
			for(int i=0;i<doubarr.length;i++){
				out.write(Double.toString(doubarr[i]));
				out.newLine();
			}
			// Close the output stream
			out.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}
}
